# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
from scrapy.exporters import JsonItemExporter


class MyscrapyPipeline(object):

    def __init__(self):
        self.fileMeituan = open('meituan.json', 'wb')
        self.fileTianmao = open('tianmao.json', 'wb')
        self.fileProxy = open('StoreProxy.txt', 'a+')
        self.fileProxyRead = open('StoreProxy.txt', 'r')
        self.exporeMeituan = JsonItemExporter(self.fileMeituan, ensure_ascii=False, encoding='utf-8')
        self.exporeMeituan.start_exporting()
        self.exporeTianmao = JsonItemExporter(self.fileTianmao, ensure_ascii=False, encoding='utf-8')
        self.exporeTianmao.start_exporting()

    def process_item(self, item, spider):
        try:
            if spider.name == 'meituan':
                self.exporeMeituan.export_item(item)
            if spider.name == 'tianmao':
                self.exporeTianmao.export_item(item)
            elif spider.name == 'XiciProxy':
                address_line = item['http'] + '://' + item['ip'] + ':' + item['port'] + '\n'
                self.fileProxy.write(address_line)
                self.fileProxy.flush()
            elif spider.name == 'JiguangProxy':
                address_line = 'HTTP://' + item['address'] + '\n'
                self.fileProxy.write(address_line)
                self.fileProxy.flush()
        except Exception as e:
            print(e)
        return item

    def open_spider(self, spider):
        if spider.name == 'meituan' or spider.name == 'tianmao':
            print('StoreProxyPipeLine meituan open')
            proxy_content = self.fileProxyRead.read()
            spider.proxy_list = proxy_content.splitlines()

    def close_spider(self,spider):
        self.exporeMeituan.finish_exporting()
        self.exporeTianmao.finish_exporting()
        self.fileMeituan.close()
        self.fileTianmao.close()
        self.fileProxy.close()
        self.fileProxyRead.close()